<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构,">





  <link rel="alternate" href="/atom.xml" title="xingyys的个人站点" type="application/atom+xml">






<meta name="description" content="引言在今天的时代，特别是互联网时代。数据的查找已经遍及生活的方方面面，比如我们上网，使用百度搜索一个关键字，这就涉及到查找机制。学习了一些的数据结构之后，我们要开始将它们使用起来了。 查找的定义我们先来了解下什么查找的定义。查找(Searching)就是根据给定的某个值，在查找表中确定一个其关键字等于给定值的数据元素(或记录)。 以及它的一些概念：查找表 (Search Table)是由同一类型的">
<meta name="keywords" content="数据结构">
<meta property="og:type" content="article">
<meta property="og:title" content="数据结构之查找">
<meta property="og:url" content="http://blog.xingyys.club/2019/02/18/数据结构之查找/index.html">
<meta property="og:site_name" content="xingyys的个人站点">
<meta property="og:description" content="引言在今天的时代，特别是互联网时代。数据的查找已经遍及生活的方方面面，比如我们上网，使用百度搜索一个关键字，这就涉及到查找机制。学习了一些的数据结构之后，我们要开始将它们使用起来了。 查找的定义我们先来了解下什么查找的定义。查找(Searching)就是根据给定的某个值，在查找表中确定一个其关键字等于给定值的数据元素(或记录)。 以及它的一些概念：查找表 (Search Table)是由同一类型的">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://image.xingyys.club/blog/稠密索引.png">
<meta property="og:image" content="http://image.xingyys.club/blog/分块索引.png">
<meta property="og:image" content="http://image.xingyys.club/blog/倒排查找.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉排序树查.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉排序树查找.png">
<meta property="og:image" content="http://image.xingyys.club/blog/平衡二叉树1.png">
<meta property="og:image" content="http://image.xingyys.club/blog/LL型.png">
<meta property="og:image" content="http://image.xingyys.club/blog/LR型.png">
<meta property="og:image" content="http://image.xingyys.club/blog/平衡二叉树插入.png">
<meta property="og:updated_time" content="2019-02-21T05:18:10.076Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据结构之查找">
<meta name="twitter:description" content="引言在今天的时代，特别是互联网时代。数据的查找已经遍及生活的方方面面，比如我们上网，使用百度搜索一个关键字，这就涉及到查找机制。学习了一些的数据结构之后，我们要开始将它们使用起来了。 查找的定义我们先来了解下什么查找的定义。查找(Searching)就是根据给定的某个值，在查找表中确定一个其关键字等于给定值的数据元素(或记录)。 以及它的一些概念：查找表 (Search Table)是由同一类型的">
<meta name="twitter:image" content="http://image.xingyys.club/blog/稠密索引.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xingyys.club/2019/02/18/数据结构之查找/">





  <title>数据结构之查找 | xingyys的个人站点</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xingyys的个人站点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学习和分享</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-users"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xingyys.club/2019/02/18/数据结构之查找/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xingyys">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xingyys的个人站点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据结构之查找</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-02-18T12:14:30+08:00">
                2019-02-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>在今天的时代，特别是互联网时代。数据的查找已经遍及生活的方方面面，比如我们上网，使用百度搜索一个关键字，这就涉及到查找机制。学习了一些的数据结构之后，我们要开始将它们使用起来了。</p>
<h1 id="查找的定义"><a href="#查找的定义" class="headerlink" title="查找的定义"></a>查找的定义</h1><p>我们先来了解下什么查找的定义。<br><code>查找(Searching)就是根据给定的某个值，在查找表中确定一个其关键字等于给定值的数据元素(或记录)。</code></p>
<p>以及它的一些概念：<br><code>查找表 (Search Table)是由同一类型的数据元素(或记录)构成的集合。</code><br><code>关键字 (Key) 是数据元素中某个数据项的值，又称为键值。</code>如果关键字可以唯一地标识一个记录，则称此关键字为为主<code>关键字(Primary Key)</code>。那么对于那些可以识别多个数据元素(或记录)的关键字，我们称为<code>次关键字(Scondary Key)</code>。</p>
<p>查找表按照操作方式来分有两大种:<code>静态查找表</code>和<code>动态查找表</code>。</p>
<p><strong>静态查找表</strong><br><code>静态查找表(Static Search Table) :只作查找操作的查找表。</code>它的主要操作有：</p>
<ol>
<li>查询某个“特定的”数据元素是否在查看表中。</li>
<li>检索某个“特定的”数据元素和各种属性。</li>
</ol>
<p><strong>动态查找表</strong><br><code>动态查找表 ( Dynamic Search Table): 在查找过程中同时插入查找表中不存在的数据元素，或者从查找表中删除已经存在的某个数据元素。</code>而它的操作有：</p>
<ol>
<li>查找时插入数据元素。</li>
<li>查找时删除数据元素。</li>
</ol>
<p>接下来我们就来看看各种查找方式的实现。</p>
<h1 id="顺序查找"><a href="#顺序查找" class="headerlink" title="顺序查找"></a>顺序查找</h1><p><code>顺序查找 (Sequential Search) 又叫线性查找，是最基本的查找技术， 它的查找过程是:从表中第一个(或最后一个)记录开始 ， 逐个进行记录的关键字和给定值比较，若某个记录的关键字和给定值相等，则查找成功 ， 找到所查的记录;如果直到最后一个(或第一个)记录，其关键字和给定值比较都不等时，则表中没有所查的记录，查找不成功，返回空值 。</code><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sequential_search</span><span class="params">(l, key)</span>:</span></span><br><span class="line">    i = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> l:</span><br><span class="line">        <span class="keyword">if</span> item == key:</span><br><span class="line">            <span class="keyword">return</span> i</span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span></span><br></pre></td></tr></table></figure></p>
<p>我们分析这种查找方式，因为要循环整个表，所以时间复杂度为：<code>O(n)</code>。</p>
<h1 id="有序表查找"><a href="#有序表查找" class="headerlink" title="有序表查找"></a>有序表查找</h1><p>顺序查找虽然也能够完成要求，但是它的效率太低，满足不了性能上的要求。假如我们在一个排序好的表格中查找，效率就会高些，这也就是有序表的查找。</p>
<h2 id="折半查找"><a href="#折半查找" class="headerlink" title="折半查找"></a>折半查找</h2><p><code>折半查找 (Binary Search) 技术，又称为二分查找。宫的前提是线性表中的记录必须是关键码有序(通常从小到大有序) ，线性表必须采用顺序存储。折半查找的基本思想是:在有序表中，取中间记录作为比较对象，若给定值与中间记录的关键字相等，则查找成功;若给定值小于中间记录的关键字，则在中阔记录的左半区继续查找 i 若给定值大于中间记录的关键字，则在中间记录的右半区继续查找。不断重复上述过程，直到查找成功，或所有查找区域元记录，查找失败为止。</code><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">binary_search</span><span class="params">(l, key)</span>:</span></span><br><span class="line">    low = <span class="number">0</span></span><br><span class="line">    mid = <span class="number">0</span></span><br><span class="line">    high = len(l) - <span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> low &lt;= high:</span><br><span class="line">        mid = int((low + high) / <span class="number">2</span>)</span><br><span class="line">        <span class="keyword">if</span> key &lt; l[mid]:</span><br><span class="line">            high = mid - <span class="number">1</span></span><br><span class="line">        <span class="keyword">elif</span> key &gt; l[mid]:</span><br><span class="line">            low = mid + <span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> mid</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span></span><br></pre></td></tr></table></figure></p>
<p>相对地，折半查找的效率高于顺序查找，时间复杂度为<code>O(logn)</code>。</p>
<h2 id="插值查找"><a href="#插值查找" class="headerlink" title="插值查找"></a>插值查找</h2><p>既然有折半查找，那么我们为什么不能有1/4，1/5折呢。基于这样的想法，我们来看看插值查找。</p>
<p>插值查找(Interpolation Search)是根据要查找的关键字 key 与查找表中最大最小记录的关键字比较后的查找方法，其核心就在于插值的计算公式$ \frac{key-a[low]}{a[high]-a[low]} $。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">interpolation_search</span><span class="params">(l, key)</span>:</span></span><br><span class="line">    low = <span class="number">0</span></span><br><span class="line">    mid = <span class="number">1</span></span><br><span class="line">    high = len(l) - <span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> low &lt;= high:</span><br><span class="line">        mid = low + int((high - low) * (key - l[low]) / (l[high] - l[low])) // 插值</span><br><span class="line">        <span class="keyword">if</span> key &lt; l[mid]:</span><br><span class="line">            high = mid - <span class="number">1</span></span><br><span class="line">        <span class="keyword">elif</span> key &gt; l[mid]:</span><br><span class="line">            low = mid + <span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> mid</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span></span><br></pre></td></tr></table></figure></p>
<p>插值查找的时间复杂度也是<code>O(logn)</code>，但在表较长、关键字分布比较均匀时，要比折半查找好些。当数据分布极度不均匀时，又不合适。</p>
<h2 id="斐波那契查找"><a href="#斐波那契查找" class="headerlink" title="斐波那契查找"></a>斐波那契查找</h2><p>我们再介绍一种有序查找，斐波那契查找 (Fibonacci Search)，它是利用了黄金分割原理来实现的 。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fibonacci_search</span><span class="params">(l, key)</span>:</span></span><br><span class="line">    n = len(l)</span><br><span class="line">    k = <span class="number">0</span></span><br><span class="line">    fib = [<span class="number">0</span>, <span class="number">1</span>]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 生成斐波那契数组</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(n):</span><br><span class="line">        fib.append(fib[<span class="number">-1</span>] + fib[<span class="number">-2</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 此处 n &gt; fib[k] - 1 也是别有深意的</span></span><br><span class="line">    <span class="comment"># 若n恰好是裴波那契数列上某一项，且要查找的元素正好在最后一位，</span></span><br><span class="line">    <span class="comment"># 此时必须将数组长度填充到数列下一项的数字</span></span><br><span class="line">    <span class="keyword">while</span> n &gt; fib[k] - <span class="number">1</span>:</span><br><span class="line">        k += <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 将待查找数组填充到指定的长度</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(n, fib[k]):</span><br><span class="line">        l.append(l[<span class="number">-1</span>])</span><br><span class="line"></span><br><span class="line">    low = <span class="number">0</span></span><br><span class="line">    mid = <span class="number">0</span></span><br><span class="line">    high = n - <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> low &lt;= high:</span><br><span class="line">        <span class="comment"># 获取黄金分割位置元素下标</span></span><br><span class="line">        mid = low + fib[k - <span class="number">1</span>] - <span class="number">1</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> key &lt; l[mid]:</span><br><span class="line">            <span class="comment"># 若key比这个元素小,则key值应该在low至mid-1之间，剩下的范围个数为F(k-1)-1</span></span><br><span class="line">            high = mid - <span class="number">1</span></span><br><span class="line">            k = k - <span class="number">1</span></span><br><span class="line">        <span class="keyword">elif</span> key &gt; l[mid]:</span><br><span class="line">            <span class="comment"># 若key比这个元素大,则key至应该在mid+1至high之间，剩下的元素个数为F(k)-F(k-1)-1=F(k-2)-1</span></span><br><span class="line">            low = mid + <span class="number">1</span></span><br><span class="line">            k = k - <span class="number">2</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">if</span> mid &lt;= n:</span><br><span class="line">                <span class="keyword">return</span> mid  <span class="comment"># 若相等则说明mid即为查找到的位置。</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">return</span> n - <span class="number">1</span>  <span class="comment"># 若 mid&gt;n 说明是补全数值，返回n。</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span></span><br></pre></td></tr></table></figure></p>
<p>同样的斐波那契查找的时间复杂度为<code>O(logn)</code>，但平均性能还是要优于折半查找。</p>
<h1 id="线性索引查找"><a href="#线性索引查找" class="headerlink" title="线性索引查找"></a>线性索引查找</h1><p>上面都是针对有序表的查找。如果表的数据量增长很快要怎么处理呢？答案就是<code>索引</code>。<br>数据结构的最终目的是提高数据的处理速度，索引是为了加快查找速度而设计的一种数据结构。<code>索引就是把一个关键字与宫对应的记录相关联的过程</code>，一个索引由若干个索引项构成，每个索引项至少应包含关键字和其对应的记录在存储器中的位置等信息。索引技术是组织大型数据库以及磁盘文件的一种重要技术。<br>索引按照结构可分为：</p>
<ul>
<li>线性索引</li>
<li>树形索引</li>
<li>多级索引</li>
</ul>
<p><code>所谓的线性索引就是将索引项集合组织为线性结构，也称索引表</code>。<br>这里我们主要介绍三种线性索引:</p>
<ul>
<li>稠密索引</li>
<li>分块索引</li>
<li>倒排索引</li>
</ul>
<h2 id="稠密索引"><a href="#稠密索引" class="headerlink" title="稠密索引"></a>稠密索引</h2><p>稠密索引是指在线性索引中，将数据集中的每个记录对应一个索引项。</p>
<p><img src="http://image.xingyys.club/blog/稠密索引.png" alt=""><br>对于稠密索引这个索引表来说，索引项一定是按照关键码有序的排列。所以我们查找关键字时，就可以使用折半、插值和斐波那契对左侧表查找。这是稠密索引的优点，但是数据集非常大的情况下，因为要反复访问磁盘，所以查找性能反而下降了。</p>
<h2 id="分块索引"><a href="#分块索引" class="headerlink" title="分块索引"></a>分块索引</h2><p>稠密索引因为索引项与数据集的记录个数相同，所以空间代价很大。所以为了减少索引项的个数，我们可以对数据集分块，使其分块有序，然后对每一块建立一个索引项，这也就是<code>分块索引</code>。<br><code>分块有序，是把数据集的记录分成了若干块，并且这些块需要满足两个条件:</code></p>
<ul>
<li>块内无序，即每一块内的记录宋要求有序。</li>
<li>快间有序，因为只有块间有序，才有可能在查找时带来放率。</li>
</ul>
<p><code>对于分块有序的数据集，将每块对应一个索引项，这种索引方法叫做分块索引</code>。<br>我们定义的分块索引的索引结构分三个数据项：</p>
<ul>
<li>最大关键码</li>
<li>存储了块中的记录个数</li>
<li>用于指向块首数据元素的指针</li>
</ul>
<p><img src="http://image.xingyys.club/blog/分块索引.png" alt=""><br>在分块索引表中查找，分为两个步骤：</p>
<ol>
<li>在分块索引表中查找要查关键字所在的快。可以使用折半、插值等算法。</li>
<li>根据块首指针找到相应的块，并在块中顺序查找关键码。因为块中可以是无序<br>的，因此只能顺序查找。</li>
</ol>
<p>分块索引查找的平均查找长度为：<br>$$ ASL_{w}=L_{b}+L{w}=\frac{m+1}{2}+\frac{t+1}{2}=\frac{1}{2}(m+t)+1=\frac{1}{2}(\frac{n}{t}+t)+1 $$<br>最佳的情况就是分的块数m与块中的记录数 t 相同，$ ASL_{w}=\frac{1}{2}(\frac{n}{t}+1)+1=t+1=\sqrt{n}+1 $。</p>
<p>分块索引在兼顾了对细分块不需要有序的情况下，大大增加了整体查找的速度，所以普遍被用于数据库表查找等技术的应用当中。</p>
<h2 id="倒排索引"><a href="#倒排索引" class="headerlink" title="倒排索引"></a>倒排索引</h2><p>倒排索引可以算是最基础的搜索技术了。假如我们有两篇文章。</p>
<ol>
<li>Books and friends should be few but good (读书如交友，应求少而精。)</li>
<li>A good book is a good friend (好书如挚友。)</li>
</ol>
<p>根据文章中的单词建立一张单词表：</p>
<p><img src="http://image.xingyys.club/blog/倒排查找.png" alt=""></p>
<p>这张表就是索引表，索引项的通用结构是：</p>
<ul>
<li>次关键字，例如上面的“英文单词”。</li>
<li>记录号表，例如上面的“文章编号”。</li>
</ul>
<p><code>其中记录号表存储具有相同次关键字的所有记录的记录号 (可以是指向记录的指针或者是该记录的主关键字) 。 这样的索引方法就是倒排索引 (invened index)。</code>正是因为它是由属性值确定记录的位置才得此名。</p>
<h1 id="二叉排序树"><a href="#二叉排序树" class="headerlink" title="二叉排序树"></a>二叉排序树</h1><p>二叉排序树 ( Binary Sort Tree)，又称为二叉查找树。它或者是一棵空树，或者是具有下列性质的二叉树。</p>
<ul>
<li>若它的左子树不空，则左子树上所有结点的值均小于它的根结构的值。</li>
<li>若它的右子树不空 ，则右子树上所有结点的值均大于宫的根结点的值。</li>
<li>它的左、右树也分别为二叉排序树。</li>
</ul>
<h2 id="构建二叉排序树"><a href="#构建二叉排序树" class="headerlink" title="构建二叉排序树"></a>构建二叉排序树</h2><p>先来提供二叉排序树的结构：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 定义二叉排序树的结点</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data, left=None, right=None)</span>:</span></span><br><span class="line">        self.data = data</span><br><span class="line">        self.left = left</span><br><span class="line">        self.right = right</span><br><span class="line">		</span><br><span class="line"><span class="comment"># 二叉排序树也是二叉树，定义结构</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BinSortTree</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.root = <span class="keyword">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">is_empty</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.root <span class="keyword">is</span> <span class="keyword">None</span></span><br></pre></td></tr></table></figure></p>
<h2 id="二叉排序树的查找"><a href="#二叉排序树的查找" class="headerlink" title="二叉排序树的查找"></a>二叉排序树的查找</h2><p><img src="http://image.xingyys.club/blog/二叉排序树查.png" alt=""><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">search</span><span class="params">(self, key)</span>:</span></span><br><span class="line">    bt = self.root</span><br><span class="line">    <span class="keyword">while</span> bt <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:   <span class="comment"># 循环直到遍历所有结点</span></span><br><span class="line">        entry = bt.data</span><br><span class="line">        <span class="keyword">if</span> key &lt; entry:     <span class="comment"># 关键字小于该节点，左子树继续查找</span></span><br><span class="line">            bt = bt.left</span><br><span class="line">        <span class="keyword">elif</span> key &gt; entry:   <span class="comment"># 关键字大于该节点，右子树继续查找</span></span><br><span class="line">            bt = bt.right</span><br><span class="line">        <span class="keyword">else</span>:               <span class="comment"># 查找成功</span></span><br><span class="line">            <span class="keyword">return</span> entry</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">None</span></span><br></pre></td></tr></table></figure></p>
<h2 id="二叉排序树的插入"><a href="#二叉排序树的插入" class="headerlink" title="二叉排序树的插入"></a>二叉排序树的插入</h2><p><img src="http://image.xingyys.club/blog/二叉排序树查找.png" alt=""><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, key)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> self.is_empty():  <span class="comment"># 树为空，直接插入为根结点</span></span><br><span class="line">        self.root = Node(key)</span><br><span class="line">    bt = self.root</span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">        entry = bt.data</span><br><span class="line">        <span class="keyword">if</span> key &lt; entry:  <span class="comment"># 结点需要在左侧插入</span></span><br><span class="line">            <span class="keyword">if</span> bt.left <span class="keyword">is</span> <span class="keyword">None</span>:  <span class="comment"># 左子树为空，直接为该节点的左子树 </span></span><br><span class="line">                bt.left = Node(key)</span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            bt = bt.left  <span class="comment"># 继续查找左子树</span></span><br><span class="line">        <span class="keyword">elif</span> key &gt; entry:  <span class="comment"># 结点需要在右侧插入</span></span><br><span class="line">            <span class="keyword">if</span> bt.right <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">                bt.right = Node(key)  <span class="comment"># 右子树为空，直接为该结点的右子树</span></span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            bt = bt.right  <span class="comment"># 继续查找右子树</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            bt.data = key  <span class="comment"># 查找到关键字相等结点，直接覆盖</span></span><br><span class="line">            <span class="keyword">return</span></span><br></pre></td></tr></table></figure></p>
<h2 id="二叉排序树的删除"><a href="#二叉排序树的删除" class="headerlink" title="二叉排序树的删除"></a>二叉排序树的删除</h2><p>二叉排序树的删除就要复杂一些，它分为多种情况。</p>
<ul>
<li>删除的结点为树叶结点，直接删除就可以了。</li>
<li>删除的结点只有左子结点或右子结点，让子树移动到删除结点的位置。</li>
<li>删除的结点有左右子树，让左子树的最右结点代替删除的结点。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">delete</span><span class="params">(self, data)</span>:</span></span><br><span class="line">    p, q = <span class="keyword">None</span>, self.root</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> q:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">while</span> q <span class="keyword">and</span> q.data != data:</span><br><span class="line">        p = q</span><br><span class="line">        <span class="keyword">if</span> data &lt; q.data:</span><br><span class="line">            q = q.left</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            q = q.right</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> q:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> q.left:</span><br><span class="line">        <span class="keyword">if</span> p <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">            self.root = q.right</span><br><span class="line">        <span class="keyword">elif</span> q <span class="keyword">is</span> p.left:</span><br><span class="line">            p.left = q.right</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            p.right = q.right</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">    r = q.left</span><br><span class="line">    <span class="keyword">while</span> r.right:</span><br><span class="line">        r = r.right</span><br><span class="line">    r.right = q.right</span><br><span class="line">    <span class="keyword">if</span> p <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.root = q.left</span><br><span class="line">    <span class="keyword">elif</span> p.left <span class="keyword">is</span> q:</span><br><span class="line">        p.left = q.left</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        p.right = q.left</span><br></pre></td></tr></table></figure>
<p>同时利用二叉树的中序遍历，就能按顺序排序。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">_mid_order</span><span class="params">(self, node=None)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> node <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        node = self.root</span><br><span class="line">    <span class="keyword">if</span> node.left <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> self._mid_order(node.left):</span><br><span class="line">            <span class="keyword">yield</span> item</span><br><span class="line">    <span class="keyword">yield</span> node.data</span><br><span class="line">    <span class="keyword">if</span> node.right <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> self._mid_order(node.right):</span><br><span class="line">            <span class="keyword">yield</span> item</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">_mid_order1</span><span class="params">(self)</span>:</span></span><br><span class="line">    node, s = self.root, []</span><br><span class="line">    <span class="keyword">while</span> node <span class="keyword">or</span> s:</span><br><span class="line">        <span class="keyword">while</span> node:</span><br><span class="line">            s.append(node)</span><br><span class="line">            node = node.left</span><br><span class="line">        node = s.pop()</span><br><span class="line">        <span class="keyword">yield</span> node.data</span><br><span class="line">        node = node.right</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mid_order</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> list(self._mid_order1())</span><br></pre></td></tr></table></figure></p>
<p>二叉树排序树的性能是性能较好，查找，插入和删除都为<code>O(logn)</code>，但是也会出现极端不平衡的情况，如全部都是右子树。这种情况下的查找的时间复杂度为<code>O(n)</code>。</p>
<h1 id="平衡二叉树"><a href="#平衡二叉树" class="headerlink" title="平衡二叉树"></a>平衡二叉树</h1><p>正是因为一般二叉排序树存在极度不平衡的情况，这种情况下性能会严重下降，所以我们就需要保持二叉树的平衡性，而这种二叉树也就是平衡二叉树。</p>
<p><code>平衡二叉树 (Self-Balance Binary Search Tree 或 Height-Balance Binary Search Tree) ，是一种二叉排序树，其中每一个节点的左子树和右子树的高度差至多等于1。也称为AVL树。</code></p>
<p>我们<code>将二叉树上结点的左子树深度减去右子树深度的值称为平衡因子BF(Balance Factor)</code>，那么平衡二叉树上所有结点的平衡因乎只可能是-1、0 和 1。只要二叉树上有一个结点的平衡园子的绝对值大于1 ，则该二叉树就是不平衡的。</p>
<p>我们看下面一组图</p>
<p><img src="http://image.xingyys.club/blog/平衡二叉树1.png" alt=""><br>因为平衡二叉树的前提是它一棵二叉排序树，所以图2不是，图3的58结点的BF为2，所以也不是。图1应该也不是。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data, left=None, right=None)</span>:</span></span><br><span class="line">        self.data = data</span><br><span class="line">        self.bf = <span class="number">0</span>		<span class="comment"># 结点中包含平衡因子</span></span><br><span class="line">        self.left = left</span><br><span class="line">        self.right = right</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AVLBinTree</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.root = <span class="keyword">None</span></span><br></pre></td></tr></table></figure>
<h2 id="平衡二叉树的重平衡情况"><a href="#平衡二叉树的重平衡情况" class="headerlink" title="平衡二叉树的重平衡情况"></a>平衡二叉树的重平衡情况</h2><p>在平衡二叉树失衡之后，重新恢复有四种情况：</p>
<h3 id="LL型"><a href="#LL型" class="headerlink" title="LL型"></a>LL型</h3><p>LL型（a的左子树较高，新节点插入在a的左子树的左子树）</p>
<p><img src="http://image.xingyys.club/blog/LL型.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@staticmethod</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">LL</span><span class="params">(a, b)</span>:</span></span><br><span class="line">    a.left = b.right</span><br><span class="line">    a.right = a</span><br><span class="line">    a.bf = b.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">return</span> b</span><br></pre></td></tr></table></figure>
<h3 id="LR型"><a href="#LR型" class="headerlink" title="LR型"></a>LR型</h3><p>LR型（a的左子树较高，新结点插入在a的左子树的右子树）</p>
<p><img src="http://image.xingyys.club/blog/LR型.png" alt=""><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@staticmethod</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">LR</span><span class="params">(a, b)</span>:</span></span><br><span class="line">    c = b.right</span><br><span class="line">    a.left, b.right = c.right, c.left</span><br><span class="line">    c.left, c.right = b, a</span><br><span class="line">    <span class="keyword">if</span> c.bf == <span class="number">0</span>:  <span class="comment"># c本身就是插入结点</span></span><br><span class="line">        a.bf = b.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">elif</span> c.bf == <span class="number">1</span>:  <span class="comment"># 新节点在c的左子树</span></span><br><span class="line">        a.bf = <span class="number">-1</span></span><br><span class="line">        b.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">else</span>:  <span class="comment"># 新节点在c的右子树</span></span><br><span class="line">        a.bf = <span class="number">0</span></span><br><span class="line">        b.bf = <span class="number">1</span></span><br><span class="line">    c.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">return</span> c</span><br></pre></td></tr></table></figure></p>
<h3 id="RR型"><a href="#RR型" class="headerlink" title="RR型"></a>RR型</h3><p>RR型（a的右子树较高，新结点插入在a的右子树的右子树）<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@staticmethod</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">RR</span><span class="params">(a, b)</span>:</span></span><br><span class="line">    a.right = b.left</span><br><span class="line">    b.left = a</span><br><span class="line">    a.bf = b.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">return</span> b</span><br></pre></td></tr></table></figure></p>
<h3 id="RL型"><a href="#RL型" class="headerlink" title="RL型"></a>RL型</h3><p>RL型（a的右子树较高，新节点插入在a的右子树的左子树）<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@staticmethod</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">RL</span><span class="params">(a, b)</span>:</span></span><br><span class="line">    c = b.left</span><br><span class="line">    a.right, c.left = c.left, c.right</span><br><span class="line">    c.left, c.right = a, b</span><br><span class="line">    <span class="keyword">if</span> c.bf == <span class="number">0</span>:  <span class="comment"># c本身就是插入结点</span></span><br><span class="line">        a.bf = <span class="number">0</span></span><br><span class="line">        b.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">elif</span> c.bf == <span class="number">1</span>:  <span class="comment"># 新节点在c的左子树</span></span><br><span class="line">        a.bf = <span class="number">0</span></span><br><span class="line">        b.bf = <span class="number">-1</span></span><br><span class="line">    <span class="keyword">else</span>:  <span class="comment"># 新节点在c的右子树</span></span><br><span class="line">        a.bf = <span class="number">1</span></span><br><span class="line">        b.bf = <span class="number">0</span></span><br><span class="line">    c.bf = <span class="number">0</span></span><br><span class="line">    <span class="keyword">return</span> c</span><br></pre></td></tr></table></figure></p>
<h2 id="平衡二叉树插入"><a href="#平衡二叉树插入" class="headerlink" title="平衡二叉树插入"></a>平衡二叉树插入</h2><p>接下来我们就来看看平衡二叉树的插入操作：</p>
<p><img src="http://image.xingyys.club/blog/平衡二叉树插入.png" alt=""><br>现在考虑插入操作的具体实现，其操作过程为：</p>
<ol>
<li>查找新结点的插入位置，并在查找过程中记录遇到的最小不平衡子树的根：<ul>
<li>用一个变量a记录距插入位置最近的平衡因子非0的结点，由于可能需要修改这棵子树，在此过程中用另一个变量pa记录a的父结点。</li>
<li>如果不存在这种结点，需要考虑的a就是树根。</li>
<li>如果新结点插入后出现失衡，a就是失衡位置。</li>
<li>实际插入新结点。<ol start="2">
<li>修改从a的子结点到新结点的路径上个结点的平衡因子。</li>
</ol>
</li>
<li>由于a的定义，这段结点原来都有 BF=0。</li>
<li>插入后用一个扫描变量p从p的子结点开始遍历，如果新结点插入在p的左子树，就把p的平衡因子改为1，否则将其改为-1。<ol start="3">
<li>检查以a为根的子树是否失衡，失衡时做调整：</li>
</ol>
</li>
<li>如果a.bf == 0，插入后不会失衡，简单修改平衡因子并结束。</li>
<li>如果a.bf == 1 而且新结点插入其左子树，就出现失衡。</li>
<li>新结点在a的左子结点的左子树时做LL调整。</li>
<li>新结点在a的左子结点的右子树时做LR调整。</li>
<li>如果a.bf == -1 而且新结点在其右子树则出现失衡。</li>
<li>新结点在a的右子结点的右子树时用RR调整。</li>
<li>新结点在a的右子结点的左子树时用RL调整。<ol start="4">
<li>连接好调整后的子树，它可能应该作为整棵树的根，或作为a原来的父结点的相应方向的子结点（左子结点或右子结点）。</li>
</ol>
</li>
</ul>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, data)</span>:</span></span><br><span class="line">    a = p = self.root</span><br><span class="line">    <span class="keyword">if</span> a <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        self.root = Node(data)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    pa = q = <span class="keyword">None</span>  <span class="comment"># 维持pa，q为a，p的父节点</span></span><br><span class="line">    <span class="keyword">while</span> p <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:  <span class="comment"># 确定插入位置及最小非平衡子树</span></span><br><span class="line">        <span class="keyword">if</span> data == p.data:  <span class="comment"># data存在，直接赋值</span></span><br><span class="line">            p.data = data</span><br><span class="line">        <span class="keyword">if</span> p.bf != <span class="number">0</span>:</span><br><span class="line">            pa, a = q, p  <span class="comment"># 已知最小非平衡子树</span></span><br><span class="line">        q = p</span><br><span class="line">        <span class="keyword">if</span> data &lt; p.data:</span><br><span class="line">            p = p.left</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            p = p.right</span><br><span class="line">    <span class="comment"># q是插入点的父节点，pa，a记录最小非平衡子树</span></span><br><span class="line">    node = Node(data)</span><br><span class="line">    <span class="keyword">if</span> data &lt; q.data:</span><br><span class="line">        q.left = node  <span class="comment"># 作为左子树点</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        q.right = node  <span class="comment"># 或右子树点</span></span><br><span class="line">    <span class="comment"># 新结点已插入，a是最小不平衡子树</span></span><br><span class="line">    <span class="keyword">if</span> data &lt; a.data:  <span class="comment"># 新节点在a的左子树</span></span><br><span class="line">        p = b = a.left</span><br><span class="line">        d = <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span>:  <span class="comment"># 新结点在a的右子树</span></span><br><span class="line">        p = b = a.right</span><br><span class="line">        d = <span class="number">-1</span>  <span class="comment"># d记录新节点在a的那棵子树</span></span><br><span class="line">    <span class="comment"># 修改b到新结点路径上各节点的BF值，b为a的子节点</span></span><br><span class="line">    <span class="keyword">while</span> p != node:  <span class="comment"># node一定存在，不用判断p空</span></span><br><span class="line">        <span class="keyword">if</span> data &lt; p.data:</span><br><span class="line">            p.bf = <span class="number">1</span></span><br><span class="line">            p = p.left</span><br><span class="line">        <span class="keyword">else</span>:  <span class="comment"># p的右子树增高</span></span><br><span class="line">            p.bf = <span class="number">-1</span></span><br><span class="line">            p = p.right</span><br><span class="line">    <span class="keyword">if</span> a.bf == <span class="number">0</span>:  <span class="comment"># a的原bf为0，不会失衡</span></span><br><span class="line">        a.bf = d</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">if</span> a.bf == -d:  <span class="comment"># 新节点在较低的子树里</span></span><br><span class="line">        a.bf = <span class="number">0</span></span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="comment"># 新结点在较高子树，失衡，必须调整</span></span><br><span class="line">    <span class="keyword">if</span> d == <span class="number">1</span>:  <span class="comment"># 新结点在a的左子树里</span></span><br><span class="line">        <span class="keyword">if</span> b.bf == <span class="number">1</span>:</span><br><span class="line">            b = AVLBinTree.LL(a, b)  <span class="comment"># LL调整</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            b = AVLBinTree.LR(a, b)  <span class="comment"># LR调整</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">if</span> b.bf == <span class="number">-1</span>:</span><br><span class="line">            b = AVLBinTree.RR(a, b)  <span class="comment"># RR调整</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            b = AVLBinTree.RL(a, b)  <span class="comment"># RL调整</span></span><br><span class="line">    <span class="keyword">if</span> pa <span class="keyword">is</span> <span class="keyword">None</span>:  <span class="comment"># 原a为树根，修改root</span></span><br><span class="line">        self.root = b</span><br><span class="line">    <span class="keyword">else</span>:  <span class="comment"># a非树根，新树接在正确位置</span></span><br><span class="line">        <span class="keyword">if</span> pa.left == a:</span><br><span class="line">            pa.left = b</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            pa.right = b</span><br></pre></td></tr></table></figure>
<h2 id="平衡二叉树的删除"><a href="#平衡二叉树的删除" class="headerlink" title="平衡二叉树的删除"></a>平衡二叉树的删除</h2><p>平衡二叉树的删除算法的基本实现与插入操作类似，也是先确定结点并删除，而后调整结构恢复。</p>
<ol>
<li>检索需要删除的结点。</li>
<li>把删除任意结点的问题变成删除某棵子树的最右结点的问题，为此只需找到被删结点左子树的最右结点并交换两个结点的位置。</li>
<li>实际删除结点（就是二叉排序树的删除）。</li>
<li>如果出现失衡就调整树结构，恢复平衡。</li>
</ol>
<blockquote>
<p>参考：<a href="https://www.cnblogs.com/suimeng/p/4560056.html" target="_blank" rel="noopener">平衡二叉树图解</a></p>
</blockquote>
<h2 id="红黑树"><a href="#红黑树" class="headerlink" title="红黑树"></a>红黑树</h2><p><a href="https://blog.csdn.net/z649431508/article/details/78034751" target="_blank" rel="noopener">红黑树的python实现</a></p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li>大话数据结构</li>
<li>数据结构Python实现</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="xingyys 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/数据结构/" rel="tag"># 数据结构</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/15/golang打包和解包/" rel="next" title="golang打包和解包">
                <i class="fa fa-chevron-left"></i> golang打包和解包
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/02/21/数据结构之排序/" rel="prev" title="数据结构之排序">
                数据结构之排序 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjIyNC8xODc3MQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="xingyys">
            
              <p class="site-author-name" itemprop="name">xingyys</p>
              <p class="site-description motion-element" itemprop="description">你的话是我脚前的灯，是我路上的光。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xingyys" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#引言"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#查找的定义"><span class="nav-number">2.</span> <span class="nav-text">查找的定义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#顺序查找"><span class="nav-number">3.</span> <span class="nav-text">顺序查找</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#有序表查找"><span class="nav-number">4.</span> <span class="nav-text">有序表查找</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#折半查找"><span class="nav-number">4.1.</span> <span class="nav-text">折半查找</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#插值查找"><span class="nav-number">4.2.</span> <span class="nav-text">插值查找</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#斐波那契查找"><span class="nav-number">4.3.</span> <span class="nav-text">斐波那契查找</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#线性索引查找"><span class="nav-number">5.</span> <span class="nav-text">线性索引查找</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#稠密索引"><span class="nav-number">5.1.</span> <span class="nav-text">稠密索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分块索引"><span class="nav-number">5.2.</span> <span class="nav-text">分块索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#倒排索引"><span class="nav-number">5.3.</span> <span class="nav-text">倒排索引</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二叉排序树"><span class="nav-number">6.</span> <span class="nav-text">二叉排序树</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#构建二叉排序树"><span class="nav-number">6.1.</span> <span class="nav-text">构建二叉排序树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉排序树的查找"><span class="nav-number">6.2.</span> <span class="nav-text">二叉排序树的查找</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉排序树的插入"><span class="nav-number">6.3.</span> <span class="nav-text">二叉排序树的插入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉排序树的删除"><span class="nav-number">6.4.</span> <span class="nav-text">二叉排序树的删除</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#平衡二叉树"><span class="nav-number">7.</span> <span class="nav-text">平衡二叉树</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#平衡二叉树的重平衡情况"><span class="nav-number">7.1.</span> <span class="nav-text">平衡二叉树的重平衡情况</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#LL型"><span class="nav-number">7.1.1.</span> <span class="nav-text">LL型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#LR型"><span class="nav-number">7.1.2.</span> <span class="nav-text">LR型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RR型"><span class="nav-number">7.1.3.</span> <span class="nav-text">RR型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RL型"><span class="nav-number">7.1.4.</span> <span class="nav-text">RL型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#平衡二叉树插入"><span class="nav-number">7.2.</span> <span class="nav-text">平衡二叉树插入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#平衡二叉树的删除"><span class="nav-number">7.3.</span> <span class="nav-text">平衡二叉树的删除</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#红黑树"><span class="nav-number">7.4.</span> <span class="nav-text">红黑树</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考"><span class="nav-number">8.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xingyys</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
